//
//  EditGridConnectedView.swift
//  GreenDeal
//
//  Created by Moennig Q on 29/12/2022.
//

import UIKit
import SnapKit
import RxSwift
class EditGridConnectedView: GreenNaviBarView {
    lazy var disposeBag = DisposeBag()
    let gridConnectedView = GridConnectedView()
    var saveBtn = OperationButton(R.string.localizable.save(),enabled: true)
    override func setUpView() {
        let contentBackView = UIView()
        contentBackView.drawCorner(byRoundingCorners: [.topLeft,.topRight])
        self.addSubview(contentBackView)
        contentBackView.snp.makeConstraints { make in
            make.top.equalTo(topBackView.snp.bottom).offset(-20)
            make.left.right.bottom.equalToSuperview()
        }
        //grid connected view
        contentBackView.addSubview(gridConnectedView)
        gridConnectedView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        //
        contentBackView.addSubview(saveBtn)
        saveBtn.snp.makeConstraints { make in
            make.bottom.equalTo(OperationButton.bottomMargin)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(48)
        }
    }
    func setData(_ model: GridConnectedViewModel){
        self.gridConnectedView.setData(model,editFlag: true)
        self.checkEverythingValid()
    }
    //MARK: - 必填项数据绑定控制continue btn是否可用
    private func checkEverythingValid(){
        //1.gridConnected
        let onGridValid = self.gridConnectedView.viewModel.rx.observe(String.self, "connected_type_value").map({
            let data = $0 ?? ""
            if data != "" {
                if $0 == GridConnectedValue.onGrid.rawValue {
                    return true
                }else{
                    return false
                }
            }else{
                return false
            }
            
        }).share(replay: 1)
        //2.nmi
        let nmiValid = self.gridConnectedView.viewModel.rx.observe(String.self, "nmi").map({
            let data = ($0 ?? "").trimmingCharacters(in: .whitespaces)
            if self.gridConnectedView.viewModel.isNMIRequired && data.count == 0 {
                return false
            }
            return true
        }).share(replay: 1)
        let everythingValid = Observable.combineLatest(
            onGridValid,
            nmiValid
        ) {
            if !$0 || ($0 && $1) {
                return true
            }
            return false
        }
        .share(replay: 1)
        everythingValid.subscribe {[weak self] (valid) in
            guard let strongSelf = self else {return}
            if valid {
                strongSelf.saveBtn.enableBtn()
            }else{
                strongSelf.saveBtn.disableBtn()
            }
        }.disposed(by: self.disposeBag)
    }
}
